package com.ruoyi.web.controller.app;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.app.domain.AppUser;
import com.ruoyi.app.domain.bo.AppLevelBo;
import com.ruoyi.app.domain.bo.AppUserBo;
import com.ruoyi.app.domain.bo.AppUserVipBo;
import com.ruoyi.app.domain.bo.SetAppParentBo;
import com.ruoyi.app.domain.vo.AppLevelVo;
import com.ruoyi.app.domain.vo.AppUserVipVo;
import com.ruoyi.app.domain.vo.AppUserVo;
import com.ruoyi.app.service.IAppLevelService;
import com.ruoyi.app.service.IAppUserImageService;
import com.ruoyi.app.service.IAppUserService;
import com.ruoyi.app.service.IAppUserVipService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.im.core.TxImTemplate;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * APP用户信息
 *
 * @author ruoyi
 * @date 2025-12-08
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/appUser")
public class AppUserController extends BaseController {


    private final IAppUserService iAppUserService;
    private final IAppLevelService appLevelService;
    private final IAppUserVipService iAppUserVipService;
    private final IAppUserImageService iAppUserImageService;

    @Autowired
    private TxImTemplate txImTemplate;

    /**
     * 查询APP用户信息列表
     */
    @SaCheckPermission("system:appUser:list")
    @GetMapping("/list")
    public TableDataInfo<AppUserVo> list(AppUserBo bo, PageQuery pageQuery) {
        List<AppLevelVo> appLevelRateVos = appLevelService.queryList(new AppLevelBo());
        Map<Long, String> level = appLevelRateVos.stream().collect(Collectors.toMap(AppLevelVo::getId, AppLevelVo::getName));
        TableDataInfo<AppUserVo> page = iAppUserService.queryPageList(bo, pageQuery);
        for (AppUserVo e : page.getData()) {
            if (e.getParentId() != null) {
                e.setParentName(iAppUserService.queryById(e.getParentId()).getUserName());
            }
            e.setVip(false);
            e.setVipTime(null);
            e.setLevelName(level.get(e.getLevel()));
            String vip = iAppUserVipService.userVip(e.getId());
            if (StringUtils.isNotBlank(vip)) {
                e.setVip(true);
                e.setVipTime(vip);
            }
            List<AppUserVo> appUserVos = iAppUserService.zhituiList(e.getId());
            List<AppUserVo> appUserVos1 = iAppUserService.jiantuiList(e.getId());
            if (bo.getTime()!=null && bo.getTime().length==2){

                String startTime = bo.getTime()[0];
                String endTime = bo.getTime()[1];

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date start = null;
                try {
                    start = sdf.parse(startTime);
                } catch (ParseException ex) {
                    throw new RuntimeException(ex);
                }
                Date end = null;
                try {
                    end = sdf.parse(endTime);
                } catch (ParseException ex) {
                    throw new RuntimeException(ex);
                }

                Date finalStart = start;
                Date finalEnd = end;
                List<AppUserVo> filtered = appUserVos.stream()
                        .filter(e2 -> {
                            Date ct = e2.getCreateTime();
                            return !ct.before(finalStart) && !ct.after(finalEnd);
                        })
                        .collect(Collectors.toList());

                List<AppUserVo> filtered2 = appUserVos1.stream()
                        .filter(e2 -> {
                            Date ct = e2.getCreateTime();
                            return !ct.before(finalStart) && !ct.after(finalEnd);
                        })
                        .collect(Collectors.toList());
                e.setZhiSum(filtered.size());
                e.setJianSum(filtered2.size());

            }else{
                e.setZhiSum(appUserVos.size());
                e.setJianSum(appUserVos1.size());
            }


            String key = "liveIf:"+ e.getId();
            if (RedisUtils.hasKey(key)){
                e.setIsRenWu(1);
            }

            String key7 = "7dayContribution:" + e.getId();
            if (RedisUtils.hasKey(key7)){
                e.setGuangGao(Integer.valueOf(RedisUtils.getCacheObject(key7).toString()));
            }






        }
        return page;
    }

    /**
     * 导出APP用户信息列表
     */
    @SaCheckPermission("system:appUser:export")
    @Log(title = "APP用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(AppUserBo bo, HttpServletResponse response) {
        List<AppUserVo> list = iAppUserService.queryList(bo);
        ExcelUtil.exportExcel(list, "APP用户信息", AppUserVo.class, response);
    }


    /**
     * 获取用户im签名
     */
    @SaCheckPermission("system:appUser:export")
    @Log(title = "获取用户im签名", businessType = BusinessType.EXPORT)
    @PostMapping("/getSign")
    public String getSign() {
        return txImTemplate.getUserSign();
    }

    @SaCheckPermission("system:appUser:export")
    @GetMapping("/getSign/{userId}")
    public String genUserSig(@PathVariable("userId") String userId) {
        String userSign = txImTemplate.getUserSign(userId);
        return userSign;
    }



    /**
     * 设置用户上级
     */
    @SaCheckPermission("system:appUser:export")
    @Log(title = "设置用户上级", businessType = BusinessType.EXPORT)
    @PostMapping("/setParent")
    public int setParent(@RequestBody SetAppParentBo bo) {
     return iAppUserService.setParent(bo);
    }

    /**
     * 获取APP用户信息详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("system:appUser:query")
    @GetMapping("/{id}")
    public R<AppUserVo> getInfo(@NotNull(message = "主键不能为空")
                                @PathVariable Long id) {
        AppUserVo appUserVo = iAppUserService.queryById(id);
        appUserVo.setVipId(Constants.SUCCESS);
        AppUserVipVo vipVo = iAppUserVipService.userVipId(appUserVo.getId());
        if (Objects.nonNull(vipVo)) {
            appUserVo.setVipId(String.valueOf(vipVo.getLevel()));
            appUserVo.setVipExpireTime(vipVo.getEndTime());
        }
        appUserVo.setPhotos(iAppUserImageService.queryList(appUserVo.getId()));
        return R.ok(appUserVo);
    }


    /**
     * 新增APP用户信息
     */
    @SaCheckPermission("system:appUser:add")
    @Log(title = "APP用户信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody AppUserBo bo) {
        return toAjax(iAppUserService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改APP用户信息
     */
    @SaCheckPermission("system:appUser:edit")
    @Log(title = "APP用户信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@RequestBody AppUserBo bo) {
        if (StringUtils.isNotBlank(bo.getPassword())) {
            bo.setPassword(BCrypt.hashpw(bo.getPassword()));
        }
        if (StringUtils.isNotBlank(bo.getAccountNumber())) {
            LambdaQueryWrapper<AppUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.ne(AppUser::getId, bo.getId());
            wrapper.eq(AppUser::getAccountNumber, bo.getAccountNumber());
            List<AppUserVo> userVos = iAppUserService.selectList(wrapper);
            if (!userVos.isEmpty()) {
                return R.fail("专属账号重复");
            }
        }
        if (bo.getVipExpireTime() != null) {
            if (bo.getVipExpireTime() < System.currentTimeMillis()) {
                return R.fail("会员时间小于当前时间不生效");
            }
            AppUserVipVo vipVo = iAppUserVipService.queryByUserId(bo.getId());
            if (Objects.nonNull(vipVo)) {
                vipVo.setEndTime(bo.getVipExpireTime());
                iAppUserVipService.updateByVo(vipVo);
            } else {
                AppUserVipBo appUserVipBo = new AppUserVipBo();
                appUserVipBo.setUserId(bo.getId());
                appUserVipBo.setEndTime(bo.getVipExpireTime());
                appUserVipBo.setExperience(0);
                iAppUserVipService.insertByBo(appUserVipBo);
            }
        }
        return toAjax(iAppUserService.updateByBo(bo) ? 1 : 0);
    }


    /**
     * 解除用户绑定
     */
    @SaCheckPermission("system:appUser:edit")
    @Log(title = "APP用户信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/unbind")
    public R<Void> unbind(@RequestBody AppUserBo bo) {
        AppUserVo userVo = iAppUserService.queryById(bo.getId());
        if (ObjectUtils.isEmpty(userVo)) {
            return R.fail("用户不存在!");
        }
        LambdaUpdateWrapper<AppUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AppUser::getId, userVo.getId());
        wrapper.set(AppUser::getUniqueCode,null);
        return iAppUserService.update(wrapper) ? R.ok() : R.fail();
    }

    /**
     * 删除APP用户信息
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:appUser:remove")
    @Log(title = "APP用户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iAppUserService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }
}
